package weibo.service;

import java.io.IOException;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import weibo.database.UserDB;
import weibo.model.UserMod;

/**
 * Servlet implementation class userlogin
 */
@WebServlet("/userlogin")
public class userlogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public userlogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		//response.sendRedirect("./login.html");
		request.getRequestDispatcher("./login.html").forward(request, response);
	}

	/**
	 * 用户登录
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		
		String login_name=request.getParameter("login_name");
		String password=request.getParameter("password");
		String ucode=request.getParameter("code").toUpperCase();
		int login_name_len=login_name.length();
		int password_len=password.length();
		
		
		
		if (login_name_len>0 && password_len>0){
			UserDB db=new UserDB();
			List<UserMod> user=db.UserLogin(login_name, password);
			HttpSession session=request.getSession(true);
			
			//验证码
			Object code=session.getAttribute("code");
			if (!ucode.equals(code)){
				System.out.println(ucode+code);
				response.getWriter().append("codeerror");
				return;
			}
			
			if (user.size()!=0){
				//加入session
				session.setAttribute("user",user);
				response.getWriter().append("success");
				System.out.println(user.get(0).getLogin_name()+" 用户已登录");
			}else{
				response.getWriter().append("error");
				System.out.println(login_name+" 用户登录失败");
			}
		}else{
			response.getWriter().append("error");
			System.out.println(login_name+" 用户登录无效登录");
		}
		
	}

}
